<?php

/*
	info: 优惠劵管理
	date: 2011-12-3
*/

if (!defined('ADMIN_WEBINROOT'))
{
	header("HTTP/1.0 404 Not Found");
	exit();
}

require WEBFILEPATH.'/include/category.class.php';
$webglobal['file_coupon'] = array();
$webglobal['file_coupon']['imagepath'] = '/upfiles/coupon/'.global_FormatTime(0, 'Ym');
$webglobal['file_coupon']['imagesetting'] = array('type'=>array('gif', 'jpg', 'jpeg', 'png', 'bmp'), 'size'=>2097152);

$categoryDataModel = CategoryDataModel::factory('coupon', array('cache' => true));
$webglobal['file_coupon']['category'] = $categoryDataModel->formatCategoryOption(0,0);

//商铺编辑
if ($webglobal['mode']=='couponedit')
{
	$webrequest['editid'] = isset($webrequest['editid']) ? intval($webrequest['editid']) : 0;
	if ($webrequest['editid'] <= 0) {
		admin_ShowMessage('不存在该优惠劵。', '', 'BACK');
	}
	$webglobal['file_coupon']['editinfo'] = $db->GetOne("SELECT * FROM {$webconfig['dbpre']}coupon WHERE id='{$webrequest['editid']}'");
	if (!$webglobal['file_coupon']['editinfo']) {
		admin_ShowMessage('不存在该优惠劵。', '', 'BACK');
	}

	if (global_CheckSubmit('adminsubmit'))
	{
		include WEBFILEPATH.'/include/upload.class.php';
		global_CheckPost(
				array(
					array('coupon_category_id,','int','isset($webglobal[\'file_coupon\'][\'category\'][@])','请选择优惠劵分类',1),
					array('status,','int','in_array(@, array(1,0,-1))','请选择优惠劵状态',1),
					array('special,','int','','',0,0),
					array('name,','str','','优惠劵名称不能为空',1,''),
					array('image_del','int','','',0,0),
					array('original,', 'num', '', '原价格式错误', 1, '0.00'),
					array('price,', 'num', '', '优惠价格式错误', 1, '0.00'),
					array('starttime', 'date', '', '开始时间必须为日期格式', 1),
					array('endtime', 'date', '', '结束时间必须为日期格式', 1),
					array('introduction,','','','优惠劵介绍不能为空',1),
			));

		if (!empty($webglobal['CPM'])) {
			admin_ShowMessage($webglobal['CPM'], '', 'BACK');
		} else {
			$webglobal['CPD']['starttime'] = empty($webglobal['CPP']['starttime']) ? $webserver['timestamp'] : global_ConvTime($webglobal['CPP']['starttime'] . ' 00:00:00');
			$webglobal['CPD']['endtime'] = empty($webglobal['CPP']['endtime']) ? $webserver['timestamp'] : global_ConvTime($webglobal['CPP']['endtime']. ' 23:59:59');

			$tempmoreshowinfo = $tempimageurl = '';
			$tempimageupload = new Upload('image', $webglobal['file_coupon']['imagesetting']);
			if ($tempimageupload->CheckFile()) {
				$tempimageupload->SaveFile(WEBFILEPATH.$webglobal['file_coupon']['imagepath']);
				$tempimageurl = $webglobal['file_coupon']['imagepath'].'/'.$tempimageupload->fileList[0]['name'];

				$imageFilePath = WEBFILEPATH.$webglobal['file_coupon']['imagepath'] . '/' . $tempimageupload->fileList[0]['name'];
				include WEBFILEPATH.'/include/image.class.php';
				$objImg = new Image();
				//Big Image:707 325
				//middle Image:188 204
				//small Image:205 133

				$bigImage = WEBFILEPATH.$webglobal['file_coupon']['imagepath'] . '/big_' . $tempimageupload->fileList[0]['name'];
				$middleImage = WEBFILEPATH.$webglobal['file_coupon']['imagepath'] . '/middle_' . $tempimageupload->fileList[0]['name'];
				$smallImage = WEBFILEPATH.$webglobal['file_coupon']['imagepath'] . '/small_' . $tempimageupload->fileList[0]['name'];

				$objImg->OnceResize($imageFilePath , 707 , 325 , $bigImage, 123, FALSE);
				$objImg->OnceResize($imageFilePath , 188 , 204 , $middleImage, 0, FALSE);
				$objImg->OnceResize($imageFilePath , 205 , 133 , $smallImage, 5, FALSE);

			} elseif (!$tempimageupload->isNone) {
				$tempmoreshowinfo .= '<br /><span class="dark">上传的logo文件不符合条件已忽略。</span>';
			}

			if ($webglobal['CPP']['image_del']>0 || $tempimageurl!='')
			{
				if ($webglobal['file_coupon']['editinfo']['image'] != '')
				{
					@unlink(WEBFILEPATH.$webglobal['file_coupon']['editinfo']['image']);
				}
				$webglobal['CPD']['image'] = $tempimageurl;
			}

			admin_CheckFromForm(ADMIN_WEBURLPATH."/index.php?mode=coupon&{$webrequest['gourl']}");
			$db->Update('coupon', '', "id='{$webrequest['editid']}'");

			cache_GetNewCoupon(true);
			cache_GetHotCoupon(true);
			cache_GetCouponDetail($webrequest['editid'], false, true);

			admin_AddLog("修改优惠劵|id: {$webrequest['editid']}");
			admin_ShowMessage("优惠劵修改成功。{$tempmoreshowinfo}", ADMIN_WEBURLPATH."/index.php?mode=coupon&{$webrequest['gourl']}");
		}
	} else {
		$webglobal['file_coupon']['gourlencode'] = urlencode($webrequest['gourl']);
		$webglobal['file_coupon']['editinfo']['starttime_show'] = !empty($webglobal['file_coupon']['editinfo']['starttime']) ? global_FormatTime($webglobal['file_coupon']['editinfo']['starttime'], 'FD') : '';
		$webglobal['file_coupon']['editinfo']['endtime_show'] = !empty($webglobal['file_coupon']['editinfo']['endtime']) ? global_FormatTime($webglobal['file_coupon']['editinfo']['endtime'], 'FD') : '';
		$webglobal['file_coupon']['editinfo']['pubtime_show'] = !empty($webglobal['file_coupon']['editinfo']['pubtime']) ? global_FormatTime($webglobal['file_coupon']['editinfo']['pubtime']) : '';
		admin_StartFromForm();
	}
}
//批量更改
elseif ($webglobal['mode']=='couponup')
{
	if (!global_CheckCome()) {
		admin_ShowMessage('参数错误。', '', 'BACK');
	}

	global_CheckPost(
				array(
					array('delid[]','int','',''),
					array('auditid[]','int','',''),
					array('access','str','','',0,'update'),
			));

	$tempauditstr = '';
	if ($webglobal['CPP']['access'] == 'update') {
		if (!empty($webglobal['CPP']['delid'])) {
			$tempauditstr = implode(',', $webglobal['CPP']['delid']);
			$db->Update('coupon', "status='1'", 'id IN ('.$db->BuildInSql($webglobal['CPP']['delid']).')');

			foreach ($webglobal['CPP']['delid'] as $couponid) {
				cache_GetCouponDetail($couponid, false, true);
			}
		}
	}
	

	$tempdelstr = '';
	if ($webglobal['CPP']['access'] == 'delete') {
		if (!empty($webglobal['CPP']['delid'])) {
			$tempdelstr = implode(',', $webglobal['CPP']['delid']);
			$db->Update('coupon', "status='-1'", 'id IN ('.$db->BuildInSql($webglobal['CPP']['delid']).')');
			
			foreach ($webglobal['CPP']['delid'] as $couponid) {
				cache_GetCouponDetail($couponid, false, true);
			}
		}
	}
	
	if ($webglobal['CPP']['access'] == 'down') {
		if (!empty($webglobal['CPP']['delid'])) {
			$tempdelstr = implode(',', $webglobal['CPP']['delid']);
			$db->Update('coupon', "status='0'", 'id IN ('.$db->BuildInSql($webglobal['CPP']['delid']).')');
			
			foreach ($webglobal['CPP']['delid'] as $couponid) {
				cache_GetCouponDetail($couponid, false, true);
			}
		}
	}
	

	$templogmsg = '';
	if (!empty($tempauditstr))
	{
		$templogmsg .= (empty($templogmsg) ? '' : '; ')."audit: {$tempauditstr}";
	}
	if (!empty($tempdelstr))
	{
		$templogmsg .= (empty($templogmsg) ? '' : '; ')."del: {$tempdelstr}";
	}
	if (empty($templogmsg))
	{
		admin_ShowMessage("没有任何条目被修改，系统自动返回。", ADMIN_WEBURLPATH."/index.php?mode=coupon&{$webrequest['gourl']}");
	}

	cache_GetNewCoupon(true);

	admin_AddLog("批量更改优惠劵|{$templogmsg}");
	admin_ShowMessage('批量更改优惠劵属性成功。', ADMIN_WEBURLPATH."/index.php?mode=coupon&{$webrequest['gourl']}");

//敏感词列表
} elseif ($webglobal['mode']=='words') {
	global_CheckPost(
				array(
					array('searchkey','str','','',0,'')
			));

	$tempsearchsql = array();
	$webglobal['file_coupon']['gourl'] = "page={$webrequest['page']}";
	$webglobal['file_coupon']['searchurl'] = "";
	if ($webglobal['CPP']['searchkey'] != '')
	{
		$tempsearchsql[] = $db->BuildSearchSql($webglobal['CPP']['searchkey'], array('find','replacement'));
		$webglobal['file_coupon']['gourl'] .= "&searchkey=".urlencode($webglobal['CPP']['searchkey']);
		$webglobal['file_coupon']['searchurl'] .= "&searchkey=".urlencode($webglobal['CPP']['searchkey']);
	}
	$tempsearchsql = empty($tempsearchsql) ? '' : ' WHERE '.implode(' AND ', $tempsearchsql);
	$webglobal['file_coupon']['gourlencode'] = urlencode($webglobal['file_coupon']['gourl']);

	$webglobal['file_coupon']['perpage'] = 10;
	$webglobal['file_coupon']['datanum'] = $db->GetNum("SELECT COUNT(*) FROM {$webconfig['dbpre']}words{$tempsearchsql}");
	if ($webglobal['file_coupon']['datanum'] > 0)
	{
		$webglobal['page'] = global_Page($webglobal['file_coupon']['datanum'], $webglobal['file_coupon']['perpage'], $webrequest['page'], ADMIN_WEBURLPATH."/index.php?mode=words{$webglobal['file_coupon']['searchurl']}&page=@@");
		$tempstartnum = ($webrequest['page']-1)*$webglobal['file_coupon']['perpage'];
		
		$query = $db->Query("SELECT * FROM {$webconfig['dbpre']}words{$tempsearchsql} LIMIT $tempstartnum, {$webglobal['file_coupon']['perpage']}");
		$temptr = 1;
		$webglobal['file_coupon']['dataarray'] = array();

		while ($tempdata = $db->FetchArray($query)) {
			$tempdata['tdclass'] = (($temptr++)%2==0) ? ' class="evenrow"' : '';
			$webglobal['file_coupon']['dataarray'][$tempdata['id']] = $tempdata;
		}
	}
} elseif ($webglobal['mode']=='wordsadd') {
	if (global_CheckSubmit('adminsubmit')) {
		global_CheckPost(
				array(
					array('find,','str','','不良词语不能为空',1),
					array('replacement,','str','','',0,'')
			));
		if (!empty($webglobal['CPM'])) {
			admin_ShowMessage($webglobal['CPM'], '', 'BACK');
		} else {
			admin_CheckFromForm(ADMIN_WEBURLPATH."/index.php?mode=words");

			$webglobal['CPD']['admin_user_id'] = $user['adminuid'];
			$tempnewsid = $db->Insert('words', '', TRUE);

			admin_AddLog("添加敏感词|id: {$tempnewsid}; find: {$webglobal['CPP']['find']}; relacement: {$webglobal['CPP']['replacement']}");
			admin_ShowMessage('敏感词添加成功。', ADMIN_WEBURLPATH."/index.php?mode=words");
		}
	} else {
		admin_StartFromForm();
	}

} elseif ($webglobal['mode']=='wordsup') {
	if (!global_CheckCome()) {
		admin_ShowMessage('参数错误。', '', 'BACK');
	}

	global_CheckPost(
				array(
					array('delid[]','int','',''),
					array('find[]','str','','不良词语不能为空',1),
					array('replacement[]','str','','',0,''),
			));
	
	if (!empty($webglobal['CPM'])) {
		admin_ShowMessage($webglobal['CPM'], '', 'BACK');
	}

	$tempdelstr = '';
	if (!empty($webglobal['CPP']['delid'])) {
		$tempdelstr = implode(',', $webglobal['CPP']['delid']);
		$db->Delete('words', 'id IN ('.$db->BuildInSql($webglobal['CPP']['delid']).')');
	}

	$tempeditarray = array();
	if (!empty($webglobal['CPP']['find']))
	{
		$temphaveid = implode(',', array_keys($webglobal['CPP']['find']));
		//查询修改前的数据
		$query = $db->Query("SELECT * FROM {$webconfig['dbpre']}words WHERE id IN ({$temphaveid})");
		$webglobal['file_coupon']['dataarray'] = array();
		while ($tempdata = $db->FetchArray($query)) {
			$webglobal['file_coupon']['dataarray'][$tempdata['id']] = $tempdata;
		}

		foreach ($webglobal['CPP']['find'] as $tempeditid => $tempeditvalue) {
			if (($tempdelstr=='' || !global_CheckHaveVar($tempdelstr, $tempeditid)) && ($tempeditvalue!=$webglobal['file_coupon']['dataarray'][$tempeditid]['find'] || $webglobal['CPP']['replacement'][$tempeditid]!=$webglobal['file_coupon']['dataarray'][$tempeditid]['replacement'])) {
				$db->Update('words', array('find'=>$tempeditvalue,'replacement'=>$webglobal['CPP']['replacement'][$tempeditid]), "id='{$tempeditid}'");
				$tempeditarray[] = $tempeditid;
			}
		}
	}
	$templogmsg = '';
	if (!empty($tempdelstr))
	{
		$templogmsg .= (empty($templogmsg) ? '' : '; ')."del: {$tempdelstr}";
	}
	if (!empty($tempeditarray))
	{
		$templogmsg .= (empty($templogmsg) ? '' : '; ')."edit: ".implode(',', $tempeditarray);
	}
	if (empty($templogmsg))
	{
		admin_ShowMessage("没有任何条目被修改，系统自动返回。", ADMIN_WEBURLPATH."/index.php?mode=words&{$webrequest['gourl']}");
	}
	admin_AddLog("批量更改敏感词|{$templogmsg}");
	admin_ShowMessage('批量更改敏感词成功。', ADMIN_WEBURLPATH."/index.php?mode=words&{$webrequest['gourl']}");
//列表
} elseif ($webglobal['mode']=='coupon') {
	global_CheckPost(
				array(
					array('order','str','','',0,''),
					array('searchkey','str','','',0,''),
					array('class','int','','',0,0),
					array('status','int','','',0,999)
			));

	$tempsearchsql = array();
	$webglobal['file_coupon']['gourl'] = "page={$webrequest['page']}";
	$webglobal['file_coupon']['searchurl'] = "";
	if ($webglobal['CPP']['class'] > 0)
	{
		$tempsearchsql[] = "coupon_category_id='{$webglobal['CPP']['class']}'";
		$webglobal['file_coupon']['gourl'] .= "&class={$webglobal['CPP']['class']}";
		$webglobal['file_coupon']['searchurl'] .= "&class={$webglobal['CPP']['class']}";
	}
	if ($webglobal['CPP']['status'] != 999)
	{
		$tempsearchsql[] = "status='{$webglobal['CPP']['status']}'";
		$webglobal['file_coupon']['gourl'] .= "&status={$webglobal['CPP']['status']}";
		$webglobal['file_coupon']['searchurl'] .= "&status={$webglobal['CPP']['status']}";
	}
	if ($webglobal['CPP']['searchkey'] != '')
	{
		$tempsearchsql[] = $db->BuildSearchSql($webglobal['CPP']['searchkey'], array('name','introduction'));
		$webglobal['file_coupon']['gourl'] .= "&searchkey=".urlencode($webglobal['CPP']['searchkey']);
		$webglobal['file_coupon']['searchurl'] .= "&searchkey=".urlencode($webglobal['CPP']['searchkey']);
	}
	if ($webglobal['CPP']['order'] != '')
	{
		$webglobal['file_coupon']['gourl'] .= "&order={$webglobal['CPP']['order']}";
	}
	$tempsearchsql = empty($tempsearchsql) ? '' : ' WHERE '.implode(' AND ', $tempsearchsql);
	$webglobal['file_coupon']['gourlencode'] = urlencode($webglobal['file_coupon']['gourl']);

	$webglobal['file_coupon']['perpage'] = 10;
	$webglobal['file_coupon']['datanum'] = $db->GetNum("SELECT COUNT(*) FROM {$webconfig['dbpre']}coupon{$tempsearchsql}");
	if ($webglobal['file_coupon']['datanum'] > 0)
	{
		$webglobal['page'] = global_Page($webglobal['file_coupon']['datanum'], $webglobal['file_coupon']['perpage'], $webrequest['page'], ADMIN_WEBURLPATH."/index.php?mode=coupon&order={$webglobal['CPP']['order']}{$webglobal['file_coupon']['searchurl']}&page=@@");
		$tempstartnum = ($webrequest['page']-1)*$webglobal['file_coupon']['perpage'];
		switch ($webglobal['CPP']['order'])
		{
			case 'id':
				$temporderstr = "id DESC";
				break;
			case 'pubtime':
				$temporderstr = "pubtime DESC,id DESC";
				break;
			default:
				$temporderstr = "id DESC";
		}
		$query = $db->Query("SELECT * FROM {$webconfig['dbpre']}coupon{$tempsearchsql} ORDER BY {$temporderstr} LIMIT $tempstartnum, {$webglobal['file_coupon']['perpage']}");
		$temptr = 1;
		$webglobal['file_coupon']['dataarray'] = array();
		$tempCompanyId = array();

		while ($tempdata = $db->FetchArray($query)) {
			$tempCompanyId[] = $tempdata['company_id'];
			$tempdata['tdclass'] = (($temptr++)%2==0) ? ' class="evenrow"' : '';
			$tempdata['starttime_show'] = !empty($tempdata['starttime']) ? global_FormatTime($tempdata['starttime'], 'FD') : '';
			$tempdata['endtime_show'] = !empty($tempdata['endtime']) ? global_FormatTime($tempdata['endtime'], 'FD') : '';
			$tempdata['pubtime_show'] = !empty($tempdata['pubtime']) ? global_FormatTime($tempdata['pubtime']) : '';
			$webglobal['file_coupon']['dataarray'][$tempdata['id']] = $tempdata;
		}

		$webglobal['file_coupon']['company'] = array();
		$tempCompanyId = array_unique($tempCompanyId);
		if ($tempCompanyId) {
			$query = $db->Query("SELECT id, name, english_name FROM {$webconfig['dbpre']}company WHERE id IN (" . $db->BuildInSql($tempCompanyId) .")");
			while ($tempdata = $db->FetchArray($query)) {
				$webglobal['file_coupon']['company'][$tempdata['id']] = $tempdata;
			}
		}
	}
}

template_Display('coupon', 1);
